﻿namespace Xms.Abp.Components;

public partial class ConditionView
{
    private ConditionModel _value;
    [Parameter]
    public ConditionModel Value
    {
        get => _value;
        set
        {
            if (_value == value) return;
            _value = value;
            if (ValueChanged.HasDelegate)
            {
                ValueChanged.InvokeAsync(value);
            }
            StateHasChanged();
        }
    }
    [Parameter] public EventCallback<ConditionModel> ValueChanged { get; set; }
    [Parameter] public List<ConditionField> ConditionFields { get; set; }
    [Parameter] public bool ReadOnly { get; set; }

    private void OnAddGroup(int index)
    {
        AddModel(index, new ConditionModel
        {
            Type = ConditionType.Group,
            Relation = ConditinRelation.And,
        });
    }

    private void OnAdd(int index)
    {
        var field = ConditionFields[0];
        AddModel(index, new ConditionModel
        {
            Type = ConditionType.Condition,
            Condition = new ConditionValue
            {
                Field = field.Field,
                CompareDataType = field.CompareDataType,
                CompareType = CompareType.Equals,
            },
        });
    }

    private void AddModel(int index, ConditionModel model)
    {
        var temp = new List<ConditionModel>(Value.Group);
        Value.Group.Clear();
        temp.Insert(index, model);
        for (int i = 0; i < temp.Count; i++)
        {
            temp[i].Index = i + 1;
        }
        Value.Group.AddRange(temp);
    }

    private void OnSub(ConditionModel model)
    {
        var temp = new List<ConditionModel>(Value.Group);
        Value.Group.Clear();
        temp.Remove(model);
        for (int i = 0; i < temp.Count; i++)
        {
            temp[i].Index = i + 1;
        }
        Value.Group.AddRange(temp);
    }
}
